package kom.GameTimer;

import java.util.LinkedList;
import java.util.List;

public class GameTimer {

    private List<GameTask> tasks = new LinkedList<GameTask>();

    public void addTask(GameTask t) {
        if (tasks.isEmpty()) {
            tasks.add(t);
        }
        if (t.executionTime > tasks.get(tasks.size() - 1).executionTime) {
            tasks.add(tasks.size(), t);
            return;
        }
        for (int index = 0; index < tasks.size(); index++) {
            if (tasks.get(index).executionTime > t.executionTime) {
                tasks.add(index, t);
                break;
            }
        }
    }
    private List<GameTask> hasRunned = new LinkedList<GameTask>();

    public void tick() {
        if (tasks.size() == 0) {
            return;
        }
        for (int index = 0; index < tasks.size(); index++) {
            if (tasks.get(index).executionTime <= System.currentTimeMillis()) {
                tasks.get(index).run();
                hasRunned.add(tasks.get(index));
                if (index != tasks.size() - 1) {
                    if (tasks.get(index).executionTime > System.currentTimeMillis()) {
                        break;
                    }
                }
            }
        }
        for (GameTask gt : hasRunned) {
            tasks.remove(gt);
        }
        hasRunned.clear();
    }
}
